//
//  FFSendRedPacketsVC.m
//  LiMaoRedPackets
//
//  Created by JayLuo on 2020/8/21.
//

#import "FFSendRedPacketsVC.h"
#import "Masonry.h"
#import "ReactiveObjC.h"
#import "FFRedPacketsRecordCell.h"
#import <LLWallet/FFWalletVC.h>
#import <LLWallet/FFWalletManager.h>
#import "FFRedPacketsVM.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface FFSendRedPacketsVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, weak) UITextField *tf1;
@property (nonatomic, weak) UITextField *tf2;
@property (nonatomic, weak) UITextField *blessingTextField;
@property (nonatomic, weak) UILabel *tipsLabel;
@property (nonatomic, strong) UILabel *moneyLabel;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) NSString *redpacket_no;
@property(nonatomic,strong) NSString *blessing;
@end

@implementation FFSendRedPacketsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupHeader];
    [self setupBody];
}

- (void)setupHeader {
    self.title = self.redPacketsType == RedPacketsTypeGroup ? LLang(@"群红包") :LLang( @"个人红包");
    self.navigationBar.showBackButton = NO;
    __weak typeof(self) weakSelf = self;
    self.navigationBar.onBack = ^{
        [weakSelf close];
    };
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationBar.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0];
    });
    self.navigationBar.style = WKNavigationBarStyleWhite;
    
    UIButton *closeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [closeButton setTitle:LLang(@"关闭") forState:(UIControlStateNormal)];
    @weakify(self);
    [[closeButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self close];
    }];
    [self.view addSubview:closeButton];
    CGFloat statusHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(statusHeight + 5);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}

- (void)setupBody {
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, - 1000, self.view.frame.size.width, 1000)];
    bgView.layer.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0].CGColor;
    
    [self.tableView addSubview:bgView];
    
    self.view.backgroundColor = [WKApp shared].config.backgroundColor;
    
    UIView *headView = [[UIView alloc] init];
    headView.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    headView.backgroundColor = [WKApp shared].config.backgroundColor;;
    _headView = headView;
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0,0,SCREEN_WIDTH,80);
    view.layer.backgroundColor = [UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0].CGColor;
//    [headView insertSubview:view atIndex:0];
    [headView addSubview:view];
    self.tableView.tableHeaderView = headView;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(SCREEN_WIDTH/2, SCREEN_WIDTH*2 - 40 + 80) radius:SCREEN_WIDTH*2 startAngle:0 endAngle:M_PI clockwise:NO];
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.lineWidth = 10;
    pathLayer.strokeColor = [UIColor colorWithRed:230/255.0 green:204/255.0 blue:204/255.0 alpha:1.0].CGColor;
    pathLayer.path = path.CGPath;
    pathLayer.fillColor = [WKApp shared].config.backgroundColor.CGColor;
    [view.layer addSublayer:pathLayer];
    
    
//    self.view.layer.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0].CGColor;
    
    if (self.redPacketsType == RedPacketsTypeGroup) {
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[LLang(@"拼手气"),LLang(@"普通")]];
        _segmentedControl.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2-70, CGRectGetMaxY(view.frame), 140, 30);
        [_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:217/255.0 green:151/255.0 blue:32/255.0 alpha:1.0]}
                                         forState:UIControlStateNormal];
        [_segmentedControl setBackgroundImage:[self imageWithColor:[UIColor whiteColor]]
                                     forState:UIControlStateNormal
                                   barMetrics:UIBarMetricsDefault];
        
        [_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
        [_segmentedControl setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:217/255.0 green:151/255.0 blue:32/255.0 alpha:1.0]] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
        _segmentedControl.selectedSegmentIndex = 0;
        _segmentedControl.layer.borderColor = [UIColor colorWithRed:217/255.0 green:151/255.0 blue:32/255.0 alpha:1.0].CGColor;
        _segmentedControl.layer.borderWidth = 1;
        _segmentedControl.layer.cornerRadius = 15;
        _segmentedControl.layer.masksToBounds = YES;
        [_segmentedControl addTarget:self action:@selector(switchControl:) forControlEvents:(UIControlEventValueChanged)];
        [headView addSubview:_segmentedControl];
        
        // 第一行
        UIView *firstLineView = [self creatLineViewLeftLabelText:LLang(@"红包个数") placeholder:LLang(@"填写个数") rightLabelText:LLang(@"个") inputTag:1000 inputType:UIKeyboardTypeASCIICapableNumberPad];
        [firstLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_segmentedControl.mas_bottom).mas_offset(30);
            make.width.equalTo(self.view);
            make.height.equalTo(@50);
        }];
        @weakify(self);
        _tf1 = (UITextField *)[firstLineView viewWithTag:1000];
        [_tf1 becomeFirstResponder];
        [_tf1.rac_textSignal subscribeNext:^(NSString * _Nullable value) {
            @strongify(self);
            if ([value isEqualToString:@""]) {
                value = @"";
                return;
            }
            if (value.integerValue > self.membersCount) {
                value = [NSString stringWithFormat:@"%ld", self.membersCount];
            }
            self.tf1.text = value;
        }];
        UILabel *tipsLabel = [[UILabel alloc] init];
        tipsLabel.text = [NSString stringWithFormat:LLang(@"本群为%ld人群"), self.membersCount];
        tipsLabel.font = [UIFont systemFontOfSize:12];
        tipsLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        [headView addSubview:tipsLabel];
        _tipsLabel = tipsLabel;
        [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(firstLineView.mas_bottom).mas_offset(8);
            make.left.equalTo(self.view.mas_left).mas_offset(15);
            make.right.equalTo(self.view.mas_right).mas_offset(-15);
        }];
    }
    
    //  第二行
    UIView *secondLineView = [self creatLineViewLeftLabelText:LLang(@"金额") placeholder:LLang(@"填写金额") rightLabelText:@"¥" inputTag:2000 inputType:(UIKeyboardTypeDecimalPad)];
    [secondLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        if (self.redPacketsType == RedPacketsTypeGroup) {
            make.top.equalTo(_tipsLabel.mas_bottom).mas_offset(20);
        }else {
            make.top.equalTo(view.mas_bottom).mas_offset(60);
        }
        make.width.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    _tf2 = (UITextField *)[secondLineView viewWithTag:2000];
    [_tf2 becomeFirstResponder];
    @weakify(self);
    [[_tf2.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        @strongify(self);
        NSInteger valueLength = 4;
        // 包含小数点，小数点后面只允许输入两位
        if ([value containsString:@"."]) {
            NSInteger decimalPointIndex =  [value rangeOfString:@"."].location;
            valueLength = decimalPointIndex + 3;
            // 1. 第一位是小数点，默认变成 0.  允许再输入两位数字
            if (decimalPointIndex == 0) {
                value = [NSString stringWithFormat:@"0.%@",value];
            }
            
            //  2.不允许输入多个（2个及以上）小数点
            for (NSInteger i = 0; i < value.length - decimalPointIndex - 1; i++) {
                NSString *character = [value substringWithRange:NSMakeRange(decimalPointIndex + i + 1, 1)];
                if ([character isEqualToString:@"."]) {
                    value = [value stringByReplacingCharactersInRange:NSMakeRange(decimalPointIndex + i + 1, 1) withString:@""];
                }
            }
        }
        
        if (value.length > valueLength) {
            self.tf2.text = [value substringToIndex:valueLength];
        } else {
            self.tf2.text = value;
        }
        
        return value.length <= valueLength;
    }] subscribeNext:^(NSString * _Nullable value) {
        @strongify(self);
        if ([value isEqualToString:@""]) {
            value = @"0.00";
        }
        
        self.moneyLabel.text = [NSString stringWithFormat:@"¥ %.2f", value.doubleValue];
    }];
    
    // 第三行
    UIView *thirdLineView = [[UIView alloc] init];
    thirdLineView.layer.backgroundColor = [WKApp shared].config.cellBackgroundColor.CGColor;
    [headView addSubview:thirdLineView];
    [thirdLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(secondLineView.mas_bottom).mas_offset(20);
        make.width.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
    textField.placeholder = LLang(@"恭喜发财，大吉大利");
    textField.font = [UIFont systemFontOfSize:16];
    textField.textAlignment = NSTextAlignmentLeft;
    [thirdLineView addSubview:textField];
    
    _blessingTextField = textField;
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(thirdLineView).mas_offset(15);
        make.right.equalTo(thirdLineView).mas_offset(-15);
        make.centerY.equalTo(thirdLineView);
    }];
    
    // 金额
    _moneyLabel = [[UILabel alloc] init];
    _moneyLabel.text = @"¥ 0.00";
    _moneyLabel.font = [UIFont systemFontOfSize:45];
    _moneyLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:_moneyLabel];
    [_moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(thirdLineView.mas_bottom).mas_offset(40);
        make.left.equalTo(self.view.mas_left).mas_offset(15);
        make.right.equalTo(self.view.mas_right).mas_offset(-15);
    }];
    
    UIButton *sendButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [sendButton setTitle:LLang(@"塞钱进红包") forState:UIControlStateNormal];
    [sendButton setTitleColor:[UIColor colorWithRed:255/255.0 green:216/255.0 blue:145/255.0 alpha:1.0] forState:UIControlStateNormal];
    [sendButton setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:209/255.0 green:68/255.0 blue:68/255.0 alpha:1.0]] forState:UIControlStateNormal];
    sendButton.layer.cornerRadius = 5;
    sendButton.layer.masksToBounds = YES;
    [sendButton addTarget:self action:@selector(send:) forControlEvents:(UIControlEventTouchUpInside)];
    [headView addSubview:sendButton];
    [sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_moneyLabel.mas_bottom).mas_offset(20);
        make.left.equalTo(self.view.mas_left).mas_offset(70);
        make.right.equalTo(self.view.mas_right).mas_offset(-70);
        make.height.equalTo(@40);
    }];
    
    UILabel *tipsLabel2 = [[UILabel alloc] init];
    tipsLabel2.text = LLang(@"未领取的红包。将在24小时后发起退款");
    tipsLabel2.textAlignment = NSTextAlignmentCenter;
    tipsLabel2.font = [UIFont systemFontOfSize:12];
    tipsLabel2.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
    [headView addSubview:tipsLabel2];
    [tipsLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(sendButton.mas_bottom).mas_offset(10);
        make.left.equalTo(self.view.mas_left).mas_offset(15);
        make.right.equalTo(self.view.mas_right).mas_offset(-15);
    }];
}

- (UIView *)creatLineViewLeftLabelText:(NSString *)leftLabelText placeholder:(NSString *)placeholder rightLabelText:(NSString *)rightLabelText inputTag:(NSInteger)inputTag inputType:(UIKeyboardType)inputType {
    UIView *contanerView = [[UIView alloc] init];
    contanerView.frame = CGRectMake(0,0 + 30,[UIScreen mainScreen].bounds.size.width,50);
    
    contanerView.layer.backgroundColor = [WKApp shared].config.cellBackgroundColor.CGColor;
    [_headView addSubview:contanerView];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:16];
    label.text = leftLabelText;
    label.textAlignment = NSTextAlignmentLeft;
    label.alpha = 1.0;
    [contanerView addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contanerView).mas_offset(15);
        make.centerY.equalTo(contanerView);
    }];
    UILabel *label2 = [[UILabel alloc] init];
    label2.font = [UIFont systemFontOfSize:20 weight:20];
    label2.text = rightLabelText;
    label2.textAlignment = NSTextAlignmentLeft;
    label2.alpha = 1.0;
    [contanerView addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(contanerView).mas_offset(-15);
        make.centerY.equalTo(contanerView);
    }];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
    textField.tag = inputTag;
    textField.keyboardType = inputType;
    textField.placeholder = placeholder;
    textField.textAlignment = NSTextAlignmentRight;
    [contanerView addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(label2.mas_left).mas_offset(-15);
        make.width.equalTo(contanerView.mas_width).mas_offset(-150);
        make.height.equalTo(@30);
        make.centerY.equalTo(contanerView);
    }];
//    [textField setBackgroundColor:[UIColor redColor]];
    
    return contanerView;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
    if(self.onDealloc) {
        self.onDealloc();
    }
}


#pragma mark - lazy
- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        UIEdgeInsets separatorInset   = _tableView.separatorInset;
        separatorInset.right          = 0;
        _tableView.separatorInset = separatorInset;
        _tableView.backgroundColor=[UIColor clearColor];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.estimatedRowHeight = 50;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.decelerationRate = 0.1;
        [_tableView registerClass:FFRedPacketsRecordCell.class forCellReuseIdentifier:[FFRedPacketsRecordCell cellId]];
        
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FFRedPacketsRecordCell *cell =  [tableView dequeueReusableCellWithIdentifier:[FFRedPacketsRecordCell cellId]];

    return cell;
}


// MARK: Actions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_headView endEditing:YES];
}

- (void)switchControl:(UISegmentedControl *)col {
    
}

- (void)close {
    [[WKNavigationManager shared] popViewControllerAnimated:YES];
}

- (void)send:(UIButton *)sendButton {
    FFRedPacketsReq *req = [FFRedPacketsReq new];
    req.amount = [self.moneyLabel.text componentsSeparatedByString:@" "].lastObject.doubleValue * 100;
    req.blessing = _blessingTextField.text.length>0?_blessingTextField.text:LLang(@"恭喜发财，大吉大利");
    if(self.channel) {
        req.sceneID = self.channel.channelId;
        req.sceneType = self.channel.channelType;
    }
    
    self.blessing = _blessingTextField.text.length>0?_blessingTextField.text:LLang(@"恭喜发财，大吉大利");
    if (self.redPacketsType == RedPacketsTypeGroup) {
           req.type = _segmentedControl.selectedSegmentIndex == 0 ? 2:1;
    }else {
           req.type = 1;
    }
    req.num = _tf1.text.integerValue != 0 ? _tf1.text.integerValue : 1;
    __weak typeof(self) weakSelf = self;
    [[FFRedPacketsVM new] redpacketsCreate:req].then(^(NSDictionary *dict){
        NSLog(@"创建红包---\n%@", dict);
        weakSelf.redpacket_no = dict[@"redpacket_no"];
        NSInteger amount = (NSInteger)([weakSelf.moneyLabel.text componentsSeparatedByString:@" "].lastObject.doubleValue * 100);
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            [[FFWalletManager shared] ff_getPayToken:amount item:LIMPayItemRedpacket remark: LLang(@"红包") callback:^(NSString * _Nonnull payToken) {
                NSLog(@"支付的payToken->%@",payToken);
                // 从服务器获取payToken
                [[WKAPIClient sharedClient] POST:[NSString stringWithFormat:@"redpackets/%@/pay",  weakSelf.redpacket_no] parameters:@{@"pay_token":payToken?:@"" }].then(^(NSDictionary*dict){
                        // 传递参数 红包id,红包标语
                    if (weakSelf.sendPacketComplete) {
                        weakSelf.sendPacketComplete(@{@"redpacket_no": weakSelf.redpacket_no,@"blessing":weakSelf.blessing});
                            [weakSelf close];
                        }
                    
                }).catch(^(NSError *error){
                    [[WKNavigationManager shared].topViewController.view showHUDWithHide:error.domain];
                });
                
            }];
            
        });
        
       
    }).catch(^(NSError *error){
        [[WKNavigationManager shared].topViewController.view showHUDWithHide:error.domain];
    });

}


@end
